package com.yumis.service.common.utils.oss;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.yumis.service.common.enums.HttpState;
import com.yumis.service.common.exception.GlobalException;
import com.yumis.service.common.vo.Response;
import com.yumis.service.config.OSSConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Slf4j
public class OSSBootUtil {

    @Autowired
    private OSSConfig ossConfig;

    private OSSBootUtil(){}

    /**
     * oss 工具客户端
     */
    private volatile static OSSClient ossClient = null;

    /**
     * 上传文件至阿里云 OSS
     * 文件上传成功,返回文件完整访问路径
     * 文件上传失败,返回 null
     *
     * @param ossConfig oss 配置信息
     * @param file 待上传文件
     * @param fileDir 文件保存目录
     * @return oss 中的相对文件路径
     */
    public static String upload(OSSConfig ossConfig, MultipartFile file, String fileDir) throws IOException {
        initOSS(ossConfig);
        StringBuilder fileUrl = new StringBuilder();
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
        String fileName = System.currentTimeMillis() + "-" + UUID.randomUUID().toString().substring(0,18) + suffix;
        if (!fileDir.endsWith("/")) {
            fileDir = fileDir.concat("/");
        }
        fileUrl = fileUrl.append(fileDir + fileName);

        ossClient.putObject(ossConfig.getBucketName(), fileUrl.toString(), file.getInputStream());
        fileUrl = fileUrl.insert(0,ossConfig.getUrl());
        return fileUrl.toString();
    }

//    public static List<UEResponse> objectListing(OSSConfig ossConfig, String fileDir){
//        initOSS(ossConfig);
//        // 构造ListObjectsRequest请求。
//        ListObjectsRequest listObjectsRequest = new ListObjectsRequest(ossConfig.getBucketName());
//        // 设置prefix参数来获取fun目录下的所有文件。
//        listObjectsRequest.setPrefix(fileDir);
//        String nextMarker = null;
//        ObjectListing objectListing;
//        List<UEResponse> list = new ArrayList<>();
//        do {
//            objectListing = ossClient.listObjects(listObjectsRequest.withMarker(nextMarker));
//            List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
//            for (OSSObjectSummary s : sums) {
//                UEResponse ueResponse = new UEResponse();
//                ueResponse.setUrl("https://haiguan-website.oss-cn-huhehaote.aliyuncs.com/" + s.getKey());
//                list.add(ueResponse);
//            }
//            nextMarker = objectListing.getNextMarker();
//        } while (objectListing.isTruncated());
//        return list;
//    }

    /**
     * 初始化 oss 客户端
     * @param ossConfig
     * @return
     */
    private static OSSClient initOSS(OSSConfig ossConfig) {
        if (ossClient == null ) {
            synchronized (OSSBootUtil.class) {
                if (ossClient == null) {
                    ossClient = new OSSClient(ossConfig.getEndpoint(),
                            new DefaultCredentialProvider(ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret()),
                            new ClientConfiguration());
                }
            }
        }
        return ossClient;
    }

    /**
     * 删除单个文件
     * @param ossConfig
     * @param url
     */
    public static void delete(OSSConfig ossConfig,String url){
        initOSS(ossConfig);
        String tempUrl = url;
        int index = url.indexOf("com/");
        String objectName =  url.substring(index+4, tempUrl.length());
        boolean found = ossClient.doesObjectExist(ossConfig.getBucketName(), objectName);
        if(!found){
            throw new GlobalException(Response.buildResponse(HttpState.FILE_NOT_EXIST));
        }
        ossClient.deleteObject(ossConfig.getBucketName(), objectName);
    }

}
